package com.sduept.nwld.dataserver.manager.config;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.core.model.BannerInfo;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.model.ImageDocument;

@Service
public class ImageManager {
	
	@Autowired
	private SuperDAO dao;
	@Autowired
	private CommonDocumentProperties pros;
	//todo springboot
	public boolean create(BannerInfo bean,byte[] bytes){
		if(bean.getPath() != null){
			File f = new File(pros.getImagePath()+bean.getPath());
			if(!f.getParentFile().exists()){
				f.getParentFile().mkdir();
			}
			return writeFile(f, bytes);
		}
		return false;
	}
	private boolean writeFile(File file, byte[] bytes){
		BufferedOutputStream bos = null;
		boolean flage = true;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			flage = false;
		}finally{
			if (null != bos) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flage;
	}

	//todo  springboot

	public boolean delete(BannerInfo bean){
		File f = new File(pros.getImagePath()+bean.getPath());
		boolean flage = false;
		if (f.exists()) {
			flage = f.delete();
		}
		dao.delete(bean.getId(), ImageDocument.class);
		return flage;
	}
}
